package demo1;

/*
观察者模式定义了一种一对多的依赖关系，让多个观察者对象同时监听某一主题对象
这个对象再状态发生变化时，会通知所有观察者对象，使它们能够自动更新自己。
 */

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        ConcreteSubject s = new ConcreteSubject();
        s.Attache(new ConcreteObserver(s, "X"));
        s.Attache(new ConcreteObserver(s, "Y"));
        s.Attache(new ConcreteObserver(s, "Z"));

        s.setSubjectState("ABC");
        s.Notify();

    }

}

abstract class Subject{
    private List<Observer> observers = new ArrayList<Observer>();
    //增加观察者
    public void Attache(Observer observer){
        observers.add(observer);
    }
    //移除观察者
    public void Detach(Observer observer){
        observers.remove(observer);
    }
    //通知
    public void Notify(){
        for (Observer o:observers
             ) {
            o.Update();
        }
    }
}

abstract class Observer{
    public abstract void Update();
}

class ConcreteSubject extends Subject{
    private String subjectState;
    //具体被观察者状态

    public String getSubjectState() {
        return subjectState;
    }

    public void setSubjectState(String subjectState) {
        this.subjectState = subjectState;
    }

}

class ConcreteObserver extends Observer{
    private String name;
    private String observerState;
    private ConcreteSubject subject;
    public ConcreteObserver(ConcreteSubject subject, String name){
        this.subject = subject;
        this.name = name;
    }

    @Override
    public void Update() {
        observerState = subject.getSubjectState();
        System.out.println("观察者"+name+"的新状态是"+observerState);

    }

    public ConcreteSubject getSubject() {
        return subject;
    }

    public void setSubject(ConcreteSubject subject) {
        this.subject = subject;
    }
}